//
//  ChooseImageView.m
//  Homestay
//
//  Created by 邓朝中 on 2017/6/13.
//  Copyright © 2017年 ysln. All rights reserved.
//

#import "ChooseImageView.h"
#import "UserInfoService.h" 

@implementation ChooseImageView{
    
    // 标识被编辑的按钮 -1 为添加新的按钮
    NSInteger editTag;
    NSMutableArray *imageArray;
    UIActionSheet *actionSheet1;

}


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UIButton *btn = [self createButtonWithImage:kAddImage andSeletor:@selector(addNew:)];
        
        [self addSubview:btn];
        imageArray = [[NSMutableArray alloc] init];
    
    }
    return self;
}

-(NSMutableArray *)images
{
    if (_images == nil) {
        _images = [NSMutableArray array];
    }
    return _images;
}

// 添加新的控件
- (void)addNew:(UIButton *)btn
{
    // 标识为添加一个新的图片
    
    if (![self deleClose:btn]) {
        editTag = -1;
        [self callImagePicker];
    }
    
    
}

// 修改旧的控件
- (void)changeOld:(UIButton *)btn
{
    // 标识为修改(tag为修改标识)
    if (![self deleClose:btn]) {
        editTag = btn.tag;
        [self callImagePicker];
    }
}

// 删除"删除按钮"
- (BOOL)deleClose:(UIButton *)btn
{
    if (btn.subviews.count == 2) {
        [[btn.subviews lastObject] removeFromSuperview];
        [self stop:btn];
        return YES;
    }
    return NO;
}

// 调用图片选择器
- (void)callImagePicker
{
    //    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    //    imagePickerController.delegate = self;
    //    imagePickerController.allowsEditing = YES;
    //    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    //    [self.window.rootViewController presentViewController:imagePickerController animated:YES completion:^{}];
    actionSheet1 = [[UIActionSheet alloc]
                    initWithTitle:nil
                    delegate:self
                    cancelButtonTitle:@"取消"
                    destructiveButtonTitle:nil
                    otherButtonTitles:@"相册",@"拍照",nil];
    actionSheet1.actionSheetStyle = UIBarStyleDefault;
    [actionSheet1 showInView:self];
}

-(UIViewController *)getMineVC{
    
    UIView* next = [[self superview] superview];
    UIResponder *nextResponder = [next nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]])
    {
        return (UIViewController *)nextResponder;
    }
    return nil;
}


-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{

    if (buttonIndex == 0) {
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [[self getMineVC] presentViewController:imagePickerController animated:YES completion:nil];
    
    }else if (buttonIndex == 1){
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [[self getMineVC] presentViewController:imagePickerController animated:YES completion:nil];
    }
    
}

// 根据图片名称或者图片创建一个新的显示控件
- (UIButton *)createButtonWithImage:(id)imageNameOrImage andSeletor : (SEL)selector
{
    UIImage *addImage = nil;
    if ([imageNameOrImage isKindOfClass:[NSString class]]) {
        addImage = [UIImage imageNamed:imageNameOrImage];
    }
    else if([imageNameOrImage isKindOfClass:[UIImage class]])
    {
        addImage = imageNameOrImage;
    }
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addBtn setImage:addImage forState:UIControlStateNormal];
    [addBtn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    addBtn.tag = self.subviews.count;
    addBtn.layer.borderColor = KGaryColor.CGColor;
    addBtn.layer.borderWidth = 0.5;
    
    // 添加长按手势,用作删除.加号按钮不添加
    if(addBtn.tag != 0)
    {
        UILongPressGestureRecognizer *gester = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
        [addBtn addGestureRecognizer:gester];
    }
    return addBtn;
    
}


// 长按添加删除按钮
- (void)longPress : (UIGestureRecognizer *)gester
{
    if (gester.state == UIGestureRecognizerStateBegan)
    {
        UIButton *btn = (UIButton *)gester.view;
        
        UIButton *dele = [UIButton buttonWithType:UIButtonTypeCustom];
        dele.bounds = CGRectMake(0, 0, deleImageWH, deleImageWH);
        [dele setImage:[UIImage imageNamed:kAdeleImage] forState:UIControlStateNormal];
        [dele addTarget:self action:@selector(deletePic:) forControlEvents:UIControlEventTouchUpInside];
        dele.frame = CGRectMake(btn.frame.size.width - dele.frame.size.width+5, -6, dele.frame.size.width, dele.frame.size.height);
        [btn addSubview:dele];
        [self start : btn];
    }
    
}

// 长按开始抖动
- (void)start : (UIButton *)btn {
    double angle1 = -5.0 / 180.0 * M_PI;
    double angle2 = 5.0 / 180.0 * M_PI;
    CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
    anim.keyPath = @"transform.rotation";
    
    anim.values = @[@(angle1),  @(angle2), @(angle1)];
    anim.duration = 0.25;
    // 动画的重复执行次数
    anim.repeatCount = MAXFLOAT;
    
    // 保持动画执行完毕后的状态
    anim.removedOnCompletion = NO;
    anim.fillMode = kCAFillModeForwards;
    
    [btn.layer addAnimation:anim forKey:@"shake"];
}
// 停止抖动
- (void)stop : (UIButton *)btn{
    [btn.layer removeAnimationForKey:@"shake"];
}

// 删除图片
- (void)deletePic : (UIButton *)btn
{
    [self.images removeObject:[(UIButton *)btn.superview imageForState:UIControlStateNormal]];
    [btn.superview removeFromSuperview];
    if ([[self.subviews lastObject] isHidden]) {
        [[self.subviews lastObject] setHidden:NO];
    }
    
    
}

// 对所有子控件进行布局
- (void)layoutSubviews
{
    [super layoutSubviews];
    int count = self.subviews.count;
    CGFloat btnW = imageW;
    CGFloat btnH = imageH;
    int maxColumn = kMaxColumn > self.frame.size.width / imageW ? self.frame.size.width / imageW : kMaxColumn;
    CGFloat marginX = (self.frame.size.width - maxColumn * btnW) / 5;
    CGFloat marginY = marginX;
    for (int i = 0; i < count; i++) {
        UIButton *btn = self.subviews[i];
        CGFloat btnX = (i % maxColumn) * (marginX + btnW) + marginX;
        CGFloat btnY = (i / maxColumn) * (marginY + btnH) + marginY;
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
    }
    
}

#pragma mark - UIImagePickerController 代理方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = info[UIImagePickerControllerEditedImage];
    if (editTag == -1) {
        // 创建一个新的控件
        UIButton *btn = [self createButtonWithImage:image andSeletor:@selector(changeOld:)];
        [self insertSubview:btn atIndex:self.subviews.count - 1];
        [self.images addObject:image];
        if (self.subviews.count - 1 == MaxImageCount) {
            [[self.subviews lastObject] setHidden:YES];
        }
        for (UIImage *image in self.images) {
            
            [self postImageWithImage:image];
        }
    }
    else
    {
        // 根据tag修改需要编辑的控件
        UIButton *btn = (UIButton *)[self viewWithTag:editTag];
        int index = [self.images indexOfObject:[btn imageForState:UIControlStateNormal]];
        [self.images removeObjectAtIndex:index];
        [btn setImage:image forState:UIControlStateNormal];
        [self.images insertObject:image atIndex:index];
    }
    // 退出图片选择控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark上传图片
-(void)postImageWithImage:(UIImage *)image{
    
    NSString *userID = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"userID"]];
    
    UserInfoService *service = [[UserInfoService alloc] init];
    [service postCommentImage:image uid:userID CompleteBlock:^(NSDictionary *returnDic, NSError *error) {
        SLog(@"%@ error:%@",returnDic,error);
        if (error == nil) {
            
            NSString *code = [NSString stringWithFormat:@"%@",[returnDic valueForKey:@"code"]];
            NSString *msg = [NSString stringWithFormat:@"%@",[returnDic valueForKey:@"message"]];
            if ([code isEqualToString:@"0"]) {
                
                [self showSuccessView:msg];
                
                NSString *url = [NSString stringWithFormat:@"%@",returnDic[@"data"]];
                [imageArray addObject:url];
                _CallBackBlcok(imageArray);
                
            }else{
                [self showErrorView:msg];
            }
        }
    }];
}
-(void)showErrorView:(NSString *)str{
    
    
    [SVProgressHUD showErrorWithStatus:str];
    [self performSelector:@selector(SVPhidden) withObject:nil afterDelay:1.5f];
}

-(void)showSuccessView:(NSString *)str{
    
    [SVProgressHUD showSuccessWithStatus:str];
    [self performSelector:@selector(SVPhidden) withObject:nil afterDelay:1.5f];
}

-(void)SVPhidden{
    
    [SVProgressHUD dismiss];
}

@end

